<template>
  <div class="panel-container">
    <div class="header">
      绿园区供地招商平台
    </div>
    <div class="panel-side esri-widget">
      <h3>地块列表({{ count }})</h3>
      <div class="selDiv">
        <select v-model="selectedOption" class="esri-widget">
          <option value="">全部</option>
          <option v-for="item in options" :value="item.label" :key="item.label">{{ item.label }}</option>
        </select>
      </div>
      <ul id="nyc_graphics">
        <li>Loading&hellip;</li>
      </ul>
    </div>
    <div id="viewDiv"></div>
  </div>
</template>
<script setup >
import { onMounted, ref, toRaw, watch } from "vue";
import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import Graphic from "@arcgis/core/Graphic.js"
import WebTileLayer from "@arcgis/core/layers/WebTileLayer"
import Legend from "@arcgis/core/widgets/Legend"
import FeatureLayer from "@arcgis/core/layers/FeatureLayer"
import BaseMap from "@arcgis/core/BaseMap"
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils";
const tiandituKey = "57dc0d6187acfcdb217e5dc3962c91e8";

const selectedOption = ref('');
let options = ref([]);
const count = ref();
let Tools = ref([]);
onMounted(() => {
  init();
  Viewlegend();
});
let graphics;
function init() {
  let tiledLayerVec = new WebTileLayer({
    title: "t0Counties",
    urlTemplate:
      `http://{subDomain}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={col}&TILEROW={row}&TILEMATRIX={level}&tk=${tiandituKey}`,
    subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
    title: "天地图影像地图",
    visible: true
  });
  // 地图标注
  let tiledLayerPoi = new WebTileLayer({
    title: "t1Counties",
    urlTemplate: `https://{subDomain}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={col}&TILEROW={row}&TILEMATRIX={level}&tk=${tiandituKey}`,
    subDomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
    title: "天地图影像注记",
    visible: true
  });
  const baseMps = new BaseMap({
    baseLayers: [
      tiledLayerVec,
      tiledLayerPoi
    ],
    title: "basemapVec",
    id: "basemapVec",
  });
  let layers = new FeatureLayer({
    url: "https://ccschy.cn/geoscene/rest/services/%E7%BB%BF%E5%9B%AD%E5%9C%B0%E5%9D%97/MapServer/3",
    title: '地块列表',
    outFields: ["*"],
    visible: true,
    popupTemplate: {
      title: "{layer}",
      content: queryChargingStations
    }
  });
  let layders = new FeatureLayer({
    url: "https://ccschy.cn/geoscene/rest/services/%E7%BB%BF%E5%9B%AD%E5%9C%B0%E5%9D%97/MapServer/4",
    outFields: ["*"],
    visible: true,
  });
  const myMap = new Map({
    basemap: baseMps,
  });
  const view = new MapView({
    map: myMap, // References a Map instance
    container: "viewDiv", // References the ID of a DOM element
    center: [125.313642, 43.898338],
    zoom: 12,
  });
  myMap.add(layers);
  myMap.add(layders);
  let legend = new Legend({
    view: view,
    style: "card",
    layerInfos: [{
      layer: layers,
      title: "图例"
    }]
  });
  Tools.value.view = view;
  Tools.value.myMap = myMap;
  Tools.value.layers = layers;
  const listNode = document.getElementById("nyc_graphics");
  view.whenLayerView(layers).then(function (layerView) {
    let query = layers.createQuery();
    query.where = "1 = 1";
    layers.queryFeatures(query).then(function (results) {
      graphics = results.features;
      count.value = graphics.length;
      const fragment = document.createDocumentFragment();
      graphics.forEach((item, index) => {
        const attributes = item.attributes;
        const name = attributes["地块名称"];
        const li = document.createElement("li");
        li.classList.add("panel-result");
        li.tabIndex = 0;
        li.setAttribute("data-result-id", index);
        li.textContent = name;
        fragment.appendChild(li);
      })
      listNode.innerHTML = "";
      listNode.appendChild(fragment);
      attrText();
    });
    view.when(() => {
      view.popup.dockOptions = {
        buttonEnabled: false,
        position: "top-right"
      };
    });

  });
  listNode.addEventListener("click", onListClickHandler);
  view.ui.add(legend, "bottom-right");
}

//监听下拉选selectedOption值变化
watch(selectedOption, (newValue, oldValue) => {
  const listNode = document.getElementById("nyc_graphics");
  const sqlQuery = `SELECT * FROM your_table WHERE condition = '${newValue}'`;
  let layers = toRaw(Tools.value.layers);
  let query = layers.createQuery();
  if (newValue == "<其他所有值>") {
    query.where = "1 = 1 and 用地类型 not in ('全部存量','商业地块','国有存量','批而未供')";
  } else if (newValue == "") {
    query.where = "1 = 1";
  } else {
    query.where = "1 = 1 and 用地类型='" + newValue + "'";
  }
  layers.queryFeatures(query).then(function (results) {
    graphics = results.features;
    count.value = graphics.length;
    const fragment = document.createDocumentFragment();
    graphics.forEach((item, index) => {
      const attributes = item.attributes;
      const name = attributes["地块名称"];
      const li = document.createElement("li");
      li.classList.add("panel-result");
      li.tabIndex = 0;
      li.setAttribute("data-result-id", index);
      li.textContent = name;
      fragment.appendChild(li);
    })
    listNode.innerHTML = "";
    listNode.appendChild(fragment);
    layers.definitionExpression = query.where;
  });
});
function Viewlegend() {
  let url = "https://ccschy.cn/geoscene/rest/services/%E7%BB%BF%E5%9B%AD%E5%9C%B0%E5%9D%97/MapServer/legend?f=pjson";
  let data = "";
  fetch(url)
    .then(function (response) {
      return response.json();
    })
    .then(function (myJson) {
      options.value = myJson.layers[0].legend;
    });
}
function queryChargingStations(target) {
  const stats = target.graphic.attributes;
  return `
    <table class="mailTable">
      <tr>
        <td class="column">地块名称</td>
        <td>${stats['地块名称']}</td>
      </tr>
      <tr>
        <td class="column">供地方式</td>
        <td>${stats['供地方式']}</td>
      </tr>
      <tr>
        <td class="column">净地情况</td>
        <td>${stats['净地情况']}</td>
      </tr>
      <tr>
        <td class="column">用地性质</td>
        <td>${stats['性质']}</td>
      </tr>
      <tr>
        <td class="column">类型</td>
        <td>${stats['类型']}</td>
      </tr>
      <tr>
        <td class="column">四至范围</td>
        <td>${stats['面积']}</td>
      </tr>
      
    </table>
  
  `
}
function onListClickHandler(event) {
  const target = event.target;
  const resultId = target.getAttribute("data-result-id");
  const result = resultId && graphics && graphics[parseInt(resultId, 10)];
  let tools_ = toRaw(Tools.value);
  const originalPoint = result.geometry.centroid
  // originalPoint.x+=300;
  originalPoint.y += 300;
  if (result) {
    try {
      tools_.view.goTo({
        center: result.geometry.extent,
        zoom: 15
      });
      tools_.view.popup.open({
        features: [result],
        location: originalPoint,

      });
    } catch (error) {
      if (error.name != "AbortError") {
        console.error(error);
      }
    }
  }
}


function attrText() {
  let arrt = document.querySelector('.esri-attribution__powered-by');
  arrt.innerHTML = '';
  arrt.innerHTML = '技术支持：长春市测绘院';
  arrt.setAttribute('style', 'width: 100%;text-align: center;font-size:16px;')
}
</script>
<style >
#viewDiv {
  padding: 0;
  margin: 0;
  height: 100vh;
  width: 100vw;
}

.mailTable {
  width: 100%;
}

.mailTable {
  font-size: 12px;
  color: #71787e;
}

.mailTable tr td {
  height: 35px;
  line-height: 35px;
  padding: 0 10px;
  color: #fff;
  background: #2d2d2d;
}

.mailTable tr td.column {
  background-color: #081E3F;
  color: #fff;
  text-align: center;
  width: 80px;
}

/* .esri-grid .esri-grid__content {
  height: 60vh;
  width: 320px;
}

.esri-feature-table {
  height: 60vh;
} */

.panel-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.panel-side {
  padding: 2px;
  box-sizing: border-box;
  width: 300px;
  height: 67vh;
  position: absolute;
  top: 20px;
  right: 20px;
  color: #fff;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 60;
}

.panel-side h3 {
  padding: 0 20px;
  margin: 20px 0;
}

.panel-side ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.panel-side li {
  list-style: none;
  padding: 10px 20px;
  border-bottom: 1px solid #373636;
  cursor: pointer;
}

.panel-result {
  cursor: pointer;
  margin: 2px 0;
  background-color: rgba(0, 0, 0, 0.3);
}

.panel-result:hover,
.panel-result:focus {
  color: orange;
  background-color: rgba(0, 0, 0, 0.75);
}

#nyc_graphics {
  height: 56vh;
  overflow-y: auto;
}

.selDiv .esri-widget {
  width: 88%;
  height: 36px;
  margin-bottom: 12px;
}

.selDiv {
  width: 100%;
  margin: 0 auto;
  text-align: center;
}

.esri-attribution {
  line-height: 35px;
}
.header{
    position: absolute;
    z-index: 999;
    top: 0;
    height: 36px;
    width: 30%;
    background: rgb(8 33 71 / 71%);
    text-align: center;
    color: #fbfbfb;
    line-height: 36px;
    border-radius: 0px 0px 50px 50px;
    left: 35%;
    font-size: 22px;
}
</style>
